<?php
// Module Body

function sendmail_domains_generate(&$submitteddata) {
	global $cfg, $remapmail;
	// Load current files
	$sysfile['sendmail.cw'] = file_get_contents($cfg['mail_sendmail']);
	$sysfile['virtusertable'] = file_get_contents($cfg['mail_virtuser']);
	$sysfile['access'] = file_get_contents($cfg['mail_access']);

	// Load file headers
	$sysfile['sendmail.cw-header'] = file_get_contents($cfg['basedir']."/headers/localhosts");
	$sysfile['access-header'] = file_get_contents($cfg['basedir']."/headers/access");
	$sysfile['access-deny'] = file_get_contents($cfg['basedir']."/headers/access-deny");

	$temp = explode("\n### DO NOT MODIFY ###\n",$sysfile['virtusertable']);
	if (is_array($temp))
		$sysfile['virtusertable-header'] = $temp[0];
	else $sysfile['virtusertable-header'] = "";


	// New files
	$newfile['sendmail.cw'] = '# This file is automatically generated by web-cp
	# Please make custom changes to '.$cfg['basedir'].'/headers/localhosts
	# ================================================

	'.$sysfile['sendmail.cw-header'].'

	';

	$newfile['access'] = '# This file is automatically generated by web-cp
	# Please make custom changes to '.$cfg['basedir'].'/headers/access
	# ================================================

	'.$sysfile['access-header'].'
	'.$sysfile['access-deny'].'
	';

	$newfile['virtusertable'] = $sysfile['virtusertable-header']."\n### DO NOT MODIFY ###\n";

	// Initialize reseller ID
	unset($oldowner);

	// make mail config
	$dbp = mysql_query("SELECT host, domain, id, aliases FROM domains WHERE type='domain' ORDER BY priority, owner, domain");
	while ($data = mysql_fetch_array($dbp)) {
		// Prepare sendmail.cw, access, virtusertable
		$newfile['access'] .= $data['host'].".".$data['domain']." RELAY\n";
		$newfile['sendmail.cw'] .= $data['host'].".".$data['domain']."\n";

		// if domain is an alias, include it
		// GYRBO - always make @domain.com work
		//if ($data['nohost'] == "true") {
			$newfile['sendmail.cw'] .= $data['domain']."\n";
			$newfile['access'] .= $data['domain']." RELAY\n";
		$newfile['virtusertable'] .= "@".$data['host'].".".$data['domain']." %1@".$data['domain']."\n";
		//}

		// If no user has catch-all, set a catch-all error (Unknown Address)
		// GYRBO - remove host
		$dbp1 = mysql_query("SELECT username FROM users WHERE id = '".$data['id']."' AND catchall = 'true'");
		if (!mysql_num_rows($dbp1))
			$newfile['virtusertable'] .= "@".$data['domain']." error:nouser Unknown E-Mail Address\n";

		// if there is aliases, include them
		$data['aliases'] = trim($data['aliases']);
		if (strstr($data['aliases']," ") && $data['aliases'] !== '') {
			$aliases = explode(" ",$data['aliases']);
			while (current($aliases)) {
				$newfile['sendmail.cw'] .= current($aliases).".".$data['domain']."\n";
				$newfile['access'] .=  current($aliases).".".$data['domain']." RELAY\n";
				$newfile['virtusertable'] .= "@".current($aliases).".".$data['domain']." %1@".$data['domain']."\n";
				next($aliases);
			}
		}
		elseif ($data['aliases'] && $data['aliases'] !== '') {
			$newfile['sendmail.cw'] .= $data['aliases'].".".$data['domain']."\n";
			$newfile['access'] .=  $data['aliases'].".".$data['domain']." RELAY\n";
			$newfile['virtusertable'] .= "@".$data['aliases'].".".$data['domain']." %1@".$data['domain']."\n";
		}

		// Check if domain has pointers / sub-domains, set them here
		$dbp2 = mysql_query("SELECT host, domain FROM domains WHERE owner='".$data['id']."' ORDER BY domain");
		while ($subdata = mysql_fetch_array($dbp2)) {
			// :: point @domain-pointer.com to >> @main-domain.com
			// GYRBO - always make this work
			// @domain-pointer.com
			if ($subdata['domain'] != $data['domain']) {
				$newfile['virtusertable'] .= "@".$subdata['domain']." %1@".$data['domain']."\n";
				$newfile['access'] .= $subdata['domain']." RELAY\n";
				$newfile['sendmail.cw'] .= $subdata['domain']."\n";
			}
			// @www.domain.com
			$newfile['virtusertable'] .= "@".$subdata['host'].".".$subdata['domain']." %1@".$data['domain']."\n";
			$newfile['access'] .= $subdata['host'].".".$subdata['domain']." RELAY\n";
			$newfile['sendmail.cw'] .= $subdata['host'].".".$subdata['domain']."\n";
		}
	}

	// Check if there was really any update and signal which service to restart
	if ($newfile['sendmail.cw'] != $sysfile['sendmail.cw']) {
		// backup first:
		if (!file_exists($cfg['mail_sendmail'].".wcp.bak")) {
			copy($cfg['mail_sendmail'], $cfg['mail_sendmail'].".wcp.bak");
		}
		file_put_contents($cfg['mail_sendmail'],$newfile['sendmail.cw']);
		$restartmail = TRUE;
	}

	if ($newfile['virtusertable'] != $sysfile['virtusertable']) {
		// backup first:
		if (!file_exists($cfg['mail_virtuser'].".wcp.bak")) {
			copy($cfg['mail_virtuser'], $cfg['mail_virtuser'].".wcp.bak");
		}
		file_put_contents($cfg['mail_virtuser'],$newfile['virtusertable']);
		$remapmail = TRUE;
	}

	if ($newfile['access'] != $sysfile['access']) {
		// backup first:
		if (!file_exists($cfg['mail_access'].".wcp.bak")) {
			copy($cfg['mail_access'], $cfg['mail_access'].".wcp.bak");
		}
		file_put_contents($cfg['mail_access'],$newfile['access']);
		$remapmail = TRUE;
	}
	return true;
}

function sendmail_users_generate(&$submitteddata) {
	global $cfg, $remapmail;

	// Load current files
	$sysfile['alias'] = file_get_contents($cfg['mail_aliases']);
	$sysfile['virtusertable'] = file_get_contents($cfg['mail_virtuser']);

	// Load file headers
	$sysfile['alias-header'] = file_get_contents($cfg['basedir']."/headers/aliases");

	$temp = explode("\n### DO NOT MODIFY ###\n",$sysfile['virtusertable']);
	if (is_array($temp)) {
		$sysfile['virtusertable-footer'] = $temp[1];
	}
	else {
		$sysfile['virtusertable-footer'] = "";
	}

	// New files
	$newfile['alias'] = '# This file is automatically generated by web-cp
	# Please make custom changes to '.$cfg['basedir'].'/headers/alias
	# ================================================

	'.$sysfile['alias-header'].'
	';

	$newfile['virtusertable'] = '# This file is automatically generated by web-cp
	# Please make custom changes with the web panel
	# ================================================

	';

	// get domain names to map virtual mail
	unset($userdom);
	unset($domalias);
	$dbp = mysql_query("SELECT id, host, domain FROM domains");
	while ($data = mysql_fetch_array($dbp)) {
		//GYRBO - without the host. part
		$userdom[$data['id']] = $data['domain'];
		//GYRBO - prevent double aliases, etc
		$domalias[$data['id']] = array();
	}

	// Generate sorted virtusertable file
	$newfile['virtusertable'] .= "## Virtual Users Mapping\n";

	$dbp = mysql_query("SELECT aliases,username,id FROM users WHERE type != 'demo' ORDER BY username");
	while ($data = mysql_fetch_array($dbp)) {
		$unique = get_property('unix user', $data['id'], $data['username']);

		//Check if a unix user has been specified for this virtual user
		if($unique==null)
			continue;

		// write entry for the main user
		$newfile['virtusertable'] .= $data['username']."@".$userdom[$data['id']]." ".$unique."\n";
		$newfile['virtusertable'] .= $unique."@".$userdom[$data['id']]." ".$unique."\n";
		// GYRBO - make sure username isn't being used as an alias
		$domalias[$data['id']][] = $data['username'];
		$domalias[$data['id']][] = $unique;

		// if there is aliases, include them
		$data['aliases'] = trim($data['aliases']);
		if (strstr($data['aliases']," "))
			$aliases = explode(" ",$data['aliases']);
		else
			$aliases = array($data['aliases']);

		while (current($aliases)) {
			//GYRBO - fairly extreme code to prevent double aliases
			if(!in_array(current($aliases), $domalias[$data['id']])) {
				//GYRBO - this may be pretty redudant, be it's also the most dangerous part
				//Not actually required now with virtual users
				//$dbpu = mysql_query("SELECT id FROM users WHERE type != 'demo' AND username = '".current($aliases)."' LIMIT 1");
				//if(mysql_num_rows($dbpu)==0) {
					$newfile['virtusertable'] .= current($aliases)."@".$userdom[$data['id']]." ".$unique."\n";
				//}
				//GYRBO - add alias to list
				$domalias[$data['id']][] = current($aliases);
			}
			next($aliases);
		}
		/*} elseif ($data['aliases']) {
			//GYRBO - fairly extreme code to prevent double aliases
			if(!in_array($data['aliases'], $domalias[$data['id']])) {
				//GYRBO - this may be pretty redudant, be it's also the most dangerous part
				$dbpu = mysql_query("SELECT id FROM users WHERE type != 'demo' AND username = '".$data['aliases']."' LIMIT 1");
				if(mysql_num_rows($dbpu)==0) {
					$newfile['virtusertable'] .= $data['aliases']."@".$userdom[$data['id']]." ".$unique."\n";
				}
				//GYRBO - add alias to list
				$domalias[$data['id']][] = $data['aliases'];
			}
		}*/
	}

	// Generate alias file
	$dbp = mysql_query("SELECT autoreply,forward,username,aliases,catchall FROM users WHERE type != 'demo' ORDER BY username");
	while ($data = mysql_fetch_array($dbp)) {
		$data['autoreply'] = trim($data['autoreply']);
		$data['forward'] = trim($data['forward']);

		// Check for autoreply or forward, else don't do anything
		if ($data['autoreply'] OR $data['forward']) {
			$newfile['alias'] .= $unique.":";
			if ($data['autoreply']) {
				$newfile['alias'] .= ' "|'.$cfg['basedir'].'/server/autoreply.php '.$unique;
				if ($data['catchall'] == 'true')
					$newfile['alias'] .= " *";
				elseif (trim($data['aliases']));
					$newfile['alias'] .= ' '.str_replace(" ",",",trim($data['aliases']));
				$newfile['alias'] .= '", \\'.$unique;
			}
			if ($data['autoreply'] AND $data['forward'])
				$newfile['alias'] .= ", ";
			if ($data['forward'])
				$newfile['alias'] .= " ".str_replace(" ",", ",$data['forward']);
			$newfile['alias'] .= "\n";
		}
	}

	// Generate any mailing list data which is appropriate
	$mailinglistdata = array($data, $domalias, $userdom);
	$ret = array();
	$ret = call_hook('server:maillist:sendmail:generate', $mailinglistdata);

	// Append any mailing list data
	foreach($ret as $fileadditions) {
		$newfile['alias'] .= $fileadditions['alias'];
		$newfile['virtusertable'] .= $fileadditions['virtusertable'];
	}

	// Generate Catch-All
	$newfile['virtusertable'] .= "\n\n## Catch-All to Users Mapping\n";

	$dbp = mysql_query("SELECT id,username FROM users WHERE catchall = 'true' and type != 'demo' ORDER BY username");
	while ($data = mysql_fetch_array($dbp)) {
		$newfile['virtusertable'] .= "@".$userdom[$data['id']]." ".$data['username']."\n";
	}

	// finalize virtusertable
	$newfile['virtusertable'] .= "\n### DO NOT MODIFY ###\n".$sysfile['virtusertable-footer'];

	// Compare system new & current system files
	if ($newfile['virtusertable'] != $sysfile['virtusertable']) {
		// backup first:
		if (!file_exists($cfg['mail_sendmail'].".wcp.bak")) {
			copy($cfg['mail_sendmail'], $cfg['mail_sendmail'].".wcp.bak");
		}
		file_put_contents($cfg['mail_virtuser'],$newfile['virtusertable']);
		$remapmail = TRUE;
	}

	if ($newfile['alias'] != $sysfile['alias']) {
		// backup first:
		if (!file_exists($cfg['mail_aliases'].".wcp.bak")) {
			copy($cfg['mail_aliases'], $cfg['mail_aliases'].".wcp.bak");
		}
		file_put_contents($cfg['mail_aliases'],$newfile['alias']);
		$remapmail = TRUE;
	}

	return true;
}

function  sendmail_user_create(&$data) {
	global $cfg;
	$unique = get_property('unix user', $data['id'], $data['username']);
	// Handle autoreply
	if ($data['autoreply']) {
		$res = file_put_contents($cfg['basedir']."/autoresponder/".$unique,substr($data['autoreply'],0,10240)); // limit autoreply to 10k
	}
	return $res;
}

function  sendmail_user_update(&$data) {
	global $cfg;
	$unique = get_property('unix user', $data['id'], $data['username']);
	// Handle autoreply
	if ($data['autoreply']) {
		$res = file_put_contents($cfg['basedir']."/autoresponder/".$unique,substr($data['autoreply'],0,10240)); // limit autoreply to 10k
	}
	return $res;
}

function  sendmail_user_remove(&$data) {
	global $cfg;
	$unique = get_property('unix user', $data['id'], $data['username']);
	// Remove autoreply message
	if (file_exists($cfg['basedir']."/autoresponder/".$unique)) {
		$res = unlink($cfg['basedir']."/autoresponder/".$unique);
	}
	return $res;
}

function sendmail_domain_backup(&$data) {
	global $cfg;

}

// Perform a user mail backup
function sendmail_user_backup(&$data) {
	global $cfg;

	if ($data['contents']['email'] != 'on')
		return false;

	$user = $data['name'];
	// check /var/spool/mail/user
	$dir = '/var/spool/mail';
	$file = $user;
	$data['archive'] = $user.'_mail.tar';
	if (is_readable($dir.'/'.$file)) {
		exec($cfg['prog']['tar']." -c -C $dir -f /tmp/".$data['archive']." ".$file, $output, $result);
	}

	// Return file location on success
	if (!$result) {
		return $data['archive'];
	} else {
		webcp_log(3,0,'backup.php',"Failed to backup User: ".$user." - Sendmail Module",0,ECHO_LOG);
		return false;
	}
}

function  sendmail_user_suspend(&$data) {
	return true;
}

function  sendmail_user_unsuspend(&$data) {
	return true;
}

function sendmail_monitor(&$data) {
	global $cfg;
	if (file_exists($cfg['spid']['sendmail'])) {
		$pid = intval(trim(file_get_contents($cfg['spid']['sendmail'])));
		if (posix_kill($pid,0))
			$data['sendmail'] = 'up';
		else {
			$data['sendmail'] = 'down';
		}
	} else {
		$data['sendmail'] = 'down';
	}
	if ($data['sendmail'] == 'down') {
		if ($cfg['service_auto_start'] && $cfg['autostart']['sendmail']) {
			webcp_log(2,0,"monitor","service down: sendmail - attempting to start",0,$echo);
			sendmail_start();
			sleep(2);
			if (file_exists($cfg['spid']['sendmail'])) {
				$pid = intval(trim(file_get_contents($cfg['spid']['sendmail'])));
				if (posix_kill($pid,0))
					$data['sendmail'] = 'up';
				else {
					$data['sendmail'] = 'down';
				}
			} else {
				$data['sendmail'] = 'down';
			}
		}
	}
	if ($data['sendmail'] == 'down') {
		webcp_log(1,0,"monitor","service down: sendmail",0,$echo);
	}
	return true;
}

function sendmail_add_lang(&$data) {
	global $T;
	switch($data['lang']) {
		default:
			$T['sendmail service'] = 'Mail Server';
			break;
	}
}

function sendmail_add_cfg(&$cfg) {
	$cfg['spid']['sendmail']= '/var/run/sendmail.pid';
	$cfg['init']['sendmail']= '/etc/init.d/sendmail';
	$cfg['autostart']['sendmail'] = true;
}

function sendmail_stop() {
	global $cfg;
	exec($cfg['init']['sendmail'].' stop');
}

function sendmail_start() {
	global $cfg;
	exec($cfg['init']['sendmail'].' start');
}

function sendmail_restart() {
	global $cfg;
	exec($cfg['init']['sendmail'].' restart');
}
?>
